#include "plugin/DynLib.h"

#ifndef __LINUX
#  include <windows.h>
#endif

namespace KCore
{
	DynLib::~DynLib()
	{
	}

	void DynLib::load()
	{
		std::string name = _name;

#ifdef __LINUX
		if (name.substr(name.length() - 3, 3) != ".so")
			name += ".so";
#else
		if (name.substr(name.length() - 4, 4) != ".dll")
			name += ".dll";
#endif
		_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );

			
	}

	void DynLib::unload()
	{
		if( DYNLIB_UNLOAD( _hInst ) )
		{
		
		}
	}

	void* DynLib::getSymbol(  const char* name ) const throw()
	{
		return (void*)DYNLIB_GETSYM( _hInst, name );
	}

	const char* DynLib::dynlibError( void ) 
	{
#ifdef __LINUX
		std::string s(dlerror());
		return s.c_str();

#else
		LPVOID lpMsgBuf; 
		FormatMessage( 
			FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | 
			FORMAT_MESSAGE_IGNORE_INSERTS, 
			NULL, 
			GetLastError(), 
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
			(LPTSTR) &lpMsgBuf, 
			0, 
			NULL 
			); 
		std::string ret = (char*)lpMsgBuf;
		// Free the buffer.
		LocalFree( lpMsgBuf );
		return ret.c_str();
#endif

	}
};
